<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class UserConf
{
    private $user;
    
    private function __construct()
    {
        if(isset($_SESSION['user_id']))
        {
            $this->user = AccountsTable::getInstance()->findOneBy('id', $_SESSION['user_id']);
        }
    }
    
    public static function getInstance()
    {
        static $instance;
        if(!$instance)
        {
            $instance = new self();
        }
        return $instance;
    }
    
    public function registerUser($login, $password)
    {
        $user = AccountsTable::getInstance()->findOneBy('login', $login);
        if($user)
        {
            if($user->getPassword() == $password)
            {
                $this->user = $user;
                $_SESSION['user_id'] = $user->getId();
                return true;
            }
            return false;
        }
        return false;
    }
    
    public function isUserLoaded()
    {
        return ($this->user instanceof Accounts);
    }
    
    public function getUser()
    {
        if(!$this->isUserLoaded())
        {
            throw new Exception('Nie znaleziono użytkownika.');
        }
        return $this->user;
    }
    
    public function unregisterUser()
    {
        unset($_SESSION['user_id']);
        unset($this->user);
    }
}